package com.ruoyi.common.qy.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class OssService {
    public static String uploadFileVideoFromUrl(String fileUrl) throws Exception {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.CHANCEL;

        // 创建OSSClient实例
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 从URL获取文件名和扩展名
            String originalFileName = UUID.randomUUID().toString();
            String fileExtension = "";

            // 生成唯一文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + (fileExtension.isEmpty() ? ".mp3" : fileExtension);

            // 按日期分类构建路径
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = simpleDateFormat.format(new Date());
            String ossObjectName = datePath + "/" + fileName;

            // 下载文件并上传到OSS
            HttpGet httpGet = new HttpGet(fileUrl);
            try (CloseableHttpResponse response = httpClient.execute(httpGet);
                 InputStream inputStream = response.getEntity().getContent()) {

                // 检查HTTP响应状态
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IOException("Failed to download file. HTTP status: " + response.getStatusLine().getStatusCode());
                }

                // 上传到OSS
                ossClient.putObject(bucketName, ossObjectName, inputStream);

                // 生成访问URL
                return "https://" + bucketName + "." + endpoint + "/" + ossObjectName;
            }

        } finally {
            ossClient.shutdown();
        }
    }

    public static String uploadFileImageFromUrl(String fileUrl) throws Exception {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.CHANCEL;

        // 创建OSSClient实例
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 从URL获取文件名和扩展名
            String fileExtension = "";

            // 生成唯一文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + (fileExtension.isEmpty() ? ".jpeg" : fileExtension);

            // 按日期分类构建路径
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = simpleDateFormat.format(new Date());
            String ossObjectName = datePath + "/" + fileName;

            // 下载文件并上传到OSS
            HttpGet httpGet = new HttpGet(fileUrl);
            try (CloseableHttpResponse response = httpClient.execute(httpGet);
                 InputStream inputStream = response.getEntity().getContent()) {

                // 检查HTTP响应状态
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IOException("Failed to download file. HTTP status: " + response.getStatusLine().getStatusCode());
                }

                // 上传到OSS
                ossClient.putObject(bucketName, ossObjectName, inputStream);

                // 生成访问URL
                return "https://" + bucketName + "." + endpoint + "/" + ossObjectName;
            }

        } finally {
            ossClient.shutdown();
        }
    }
    /**
     * 通用 OSS 文件上传方法
     * @param multipartFile 上传的文件
     * @return 文件访问URL
     */
    public static String uploadFile(MultipartFile multipartFile,String fileName) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.CHANCEL;
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }

        OSS ossClient = null;
        try {
            // 创建OSSClient实例
             ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 生成唯一文件名
//            String originalFilename = multipartFile.getOriginalFilename();
//            String fileExtension = getFileExtension(originalFilename);
//            String fileName = generateFileName(fileExtension);

            // 完整的文件路径
            // 按日期分类构建路径
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = simpleDateFormat.format(new Date());
            String filePath = datePath + "/" + fileName;

            // 上传文件流
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    bucketName,
                    filePath,
                    inputStream
            );

            // 执行上传
            ossClient.putObject(putObjectRequest);

            // 生成文件访问URL
            String fileUrl = "https://" + bucketName + "." + endpoint + "/" + filePath;

            System.out.printf("文件上传成功: {} -> {}",fileName, fileUrl);
            return fileUrl;

        } catch (IOException e) {
            throw new ServiceException("文件上传失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 生成唯一文件名
     */
    private static String generateFileName(String fileExtension) {
        return UUID.randomUUID().toString().replace("-", "") + fileExtension;
    }

    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }
}
